package studentdemo.ui;

import studentdemo.modul.Major;
import studentdemo.modul.Class;
import studentdemo.server.MajorService;
import studentdemo.server.ClassService;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.List;

public class MajorClassPanel extends JPanel {
    private MajorService majorService = new MajorService();
    private ClassService classService = new ClassService();
    private JList<Major> majorList;
    private DefaultListModel<Major> majorListModel;
    private JTable classTable;
    private DefaultTableModel classTableModel;
    private JButton addMajorBtn, editMajorBtn, deleteMajorBtn, addClassBtn, editClassBtn, deleteClassBtn, refreshBtn;
    private String selectedMajorId = null;

    public MajorClassPanel() {
        setLayout(new BorderLayout());
        // 左侧专业列表
        majorListModel = new DefaultListModel<>();
        majorList = new JList<>(majorListModel);
        majorList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        JScrollPane majorScroll = new JScrollPane(majorList);
        majorScroll.setPreferredSize(new Dimension(200, 0));
        add(majorScroll, BorderLayout.WEST);

        // 右侧班级表格
        String[] classColumns = {"班级编号", "班级名称", "所属专业编号"};
        classTableModel = new DefaultTableModel(classColumns, 0) {
            public boolean isCellEditable(int row, int column) { return false; }
        };
        classTable = new JTable(classTableModel);
        JScrollPane classScroll = new JScrollPane(classTable);
        add(classScroll, BorderLayout.CENTER);

        // 顶部按钮区
        JPanel topPanel = new JPanel();
        addMajorBtn = new JButton("新增专业");
        editMajorBtn = new JButton("修改专业");
        deleteMajorBtn = new JButton("删除专业");
        addClassBtn = new JButton("新增班级");
        editClassBtn = new JButton("修改班级");
        deleteClassBtn = new JButton("删除班级");
        refreshBtn = new JButton("刷新");
        topPanel.add(addMajorBtn);
        topPanel.add(editMajorBtn);
        topPanel.add(deleteMajorBtn);
        topPanel.add(addClassBtn);
        topPanel.add(editClassBtn);
        topPanel.add(deleteClassBtn);
        topPanel.add(refreshBtn);
        add(topPanel, BorderLayout.NORTH);

        // 事件绑定
        majorList.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                if (e.getClickCount() == 2 || e.getClickCount() == 1) {
                    Major major = majorList.getSelectedValue();
                    if (major != null) {
                        selectedMajorId = major.getMno();
                        loadClassTable(selectedMajorId);
                    }
                }
            }
        });
        addMajorBtn.addActionListener(e -> showMajorDialog(null));
        editMajorBtn.addActionListener(e -> editMajorAction());
        deleteMajorBtn.addActionListener(e -> deleteMajorAction());
        addClassBtn.addActionListener(e -> showClassDialog(null));
        editClassBtn.addActionListener(e -> editClassAction());
        deleteClassBtn.addActionListener(e -> deleteClassAction());
        refreshBtn.addActionListener(e -> loadMajorList());

        loadMajorList();
    }

    private void loadMajorList() {
        majorListModel.clear();
        List<Major> majors = majorService.getAllMajors();
        for (Major m : majors) {
            majorListModel.addElement(m);
        }
        if (!majors.isEmpty()) {
            majorList.setSelectedIndex(0);
            selectedMajorId = majors.get(0).getMno();
            loadClassTable(selectedMajorId);
        } else {
            classTableModel.setRowCount(0);
        }
    }

    private void loadClassTable(String majorId) {
        classTableModel.setRowCount(0);
        List<Class> classes = classService.getClassesByMajor(majorId);
        for (Class c : classes) {
            classTableModel.addRow(new Object[]{c.getClno(), c.getClname(), c.getClmno()});
        }
    }

    private void showMajorDialog(Major major) {
        JTextField mnoField = new JTextField();
        JTextField mnameField = new JTextField();
        if (major != null) {
            mnoField.setText(major.getMno());
            mnoField.setEditable(false);
            mnameField.setText(major.getMname());
        }
        JPanel panel = new JPanel(new GridLayout(0, 2));
        panel.add(new JLabel("专业编号:")); panel.add(mnoField);
        panel.add(new JLabel("专业名称:")); panel.add(mnameField);
        int result = JOptionPane.showConfirmDialog(this, panel, major == null ? "新增专业" : "修改专业", JOptionPane.OK_CANCEL_OPTION);
        if (result == JOptionPane.OK_OPTION) {
            String mno = mnoField.getText().trim();
            String mname = mnameField.getText().trim();
            Major m = new Major(mno, mname);
            boolean success;
            if (major == null) {
                success = majorService.addMajor(m);
            } else {
                success = majorService.updateMajor(m);
            }
            if (success) {
                JOptionPane.showMessageDialog(this, "操作成功");
                loadMajorList();
            } else {
                JOptionPane.showMessageDialog(this, "操作失败");
            }
        }
    }

    private void editMajorAction() {
        Major major = majorList.getSelectedValue();
        if (major == null) {
            JOptionPane.showMessageDialog(this, "请先选中一个专业");
            return;
        }
        showMajorDialog(major);
    }

    private void deleteMajorAction() {
        Major major = majorList.getSelectedValue();
        if (major == null) {
            JOptionPane.showMessageDialog(this, "请先选中一个专业");
            return;
        }
        int confirm = JOptionPane.showConfirmDialog(this, "确定要删除专业 " + major.getMname() + " 吗？", "确认删除", JOptionPane.YES_NO_OPTION);
        if (confirm == JOptionPane.YES_OPTION) {
            boolean success = majorService.deleteMajor(major.getMno());
            if (success) {
                JOptionPane.showMessageDialog(this, "删除成功");
                loadMajorList();
            } else {
                JOptionPane.showMessageDialog(this, "删除失败");
            }
        }
    }

    private void showClassDialog(Class clazz) {
        JTextField clnoField = new JTextField();
        JTextField clnameField = new JTextField();
        JComboBox<Major> majorBox = new JComboBox<>();
        List<Major> majors = majorService.getAllMajors();
        for (Major m : majors) {
            majorBox.addItem(m);
        }
        if (clazz != null) {
            clnoField.setText(clazz.getClno());
            clnoField.setEditable(false);
            clnameField.setText(clazz.getClname());
            // 选中所属专业
            for (int i = 0; i < majorBox.getItemCount(); i++) {
                if (majorBox.getItemAt(i).getMno().equals(clazz.getClmno())) {
                    majorBox.setSelectedIndex(i);
                    break;
                }
            }
        } else if (selectedMajorId != null) {
            // 新增班级时默认选中当前专业
            for (int i = 0; i < majorBox.getItemCount(); i++) {
                if (majorBox.getItemAt(i).getMno().equals(selectedMajorId)) {
                    majorBox.setSelectedIndex(i);
                    break;
                }
            }
        }
        JPanel panel = new JPanel(new GridLayout(0, 2));
        panel.add(new JLabel("班级编号:")); panel.add(clnoField);
        panel.add(new JLabel("班级名称:")); panel.add(clnameField);
        panel.add(new JLabel("所属专业:")); panel.add(majorBox);
        int result = JOptionPane.showConfirmDialog(this, panel, clazz == null ? "新增班级" : "修改班级", JOptionPane.OK_CANCEL_OPTION);
        if (result == JOptionPane.OK_OPTION) {
            String clno = clnoField.getText().trim();
            String clname = clnameField.getText().trim();
            Major m = (Major) majorBox.getSelectedItem();
            if (m == null) {
                JOptionPane.showMessageDialog(this, "请选择专业");
                return;
            }
            Class c = new Class(clno, clname, m.getMno());
            boolean success;
            if (clazz == null) {
                success = classService.addClass(c);
            } else {
                success = classService.updateClass(c);
            }
            if (success) {
                JOptionPane.showMessageDialog(this, "操作成功");
                loadClassTable(m.getMno());
            } else {
                JOptionPane.showMessageDialog(this, "操作失败");
            }
        }
    }

    private void editClassAction() {
        int row = classTable.getSelectedRow();
        if (row == -1) {
            JOptionPane.showMessageDialog(this, "请先选中一个班级");
            return;
        }
        String clno = (String) classTableModel.getValueAt(row, 0);
        Class clazz = classService.getClassById(clno);
        if (clazz != null) {
            showClassDialog(clazz);
        }
    }

    private void deleteClassAction() {
        int row = classTable.getSelectedRow();
        if (row == -1) {
            JOptionPane.showMessageDialog(this, "请先选中一个班级");
            return;
        }
        String clno = (String) classTableModel.getValueAt(row, 0);
        int confirm = JOptionPane.showConfirmDialog(this, "确定要删除班级编号为" + clno + "的班级吗？", "确认删除", JOptionPane.YES_NO_OPTION);
        if (confirm == JOptionPane.YES_OPTION) {
            boolean success = classService.deleteClass(clno);
            if (success) {
                JOptionPane.showMessageDialog(this, "删除成功");
                loadClassTable(selectedMajorId);
            } else {
                JOptionPane.showMessageDialog(this, "删除失败");
            }
        }
    }
} 